
const Router = require("koa-router");

const router =  new Router();

const db = require("../db");

router.post("/api/cart/add",async (ctx,next)=>{
        let {userid,productid} = ctx.request.body;
        let data = await db.select(`select * from cart where userid="${userid}" and productid="${productid}"`);
     
        if(data.length!=0){
       	    ctx.body = {
       	    	code:1,
       	    	msg:"购物车已有该商品"
       	    }
       	    return ;
        }

        let findData = await db.select(`select * from productlist where id="${productid}"`);
        let {imgurl,title,price} = findData[0];
        let addResult = await db.add(`insert into cart (userid,img,name,price,num,isCheck,productid) values (${userid},"${imgurl}","${title}","${price}",1,0,${productid})`);
    
        if(addResult==0){
        	ctx.body = {
       	    	code:0,
       	    	msg:"添加成功"
       	    }
        }else{
        	ctx.body = {
       	    	code:1,
       	    	msg:"添加失败"
       	    }
        }	                          
})


router.get("/api/cart/:id",async (ctx,next)=>{
       let {id} = ctx.params;
       let data = await db.select(`select * from cart where userid="${id}"`);
    
       ctx.body = {
       	   code:0,
       	   data:data
       }
})


router.get("/api/cart/del/:id",async (ctx,next)=>{
      let {id} = ctx.params;
      let res = await db.del(`delete from cart where id="${id}"`);
      
      if(res==0){
        ctx.body = {
           code:0,
           msg:"删除成功"
        }
      }else{
        ctx.body = {
          code:1,
          msg:"删除失败"
        }
      }
      
})





module.exports = router;